package cn.aigoubuy.dao.ilpl;

import cn.aigoubuy.dao.ProductDao;
import cn.aigoubuy.domain.Product;
import cn.aigoubuy.utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class ProductDaoImpl implements ProductDao {
    @Override
    public List<Product> findByHot() throws SQLException {
        QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
        String sql = "select * from product where is_hot=? and pflag=? order by pdate desc limit ?";
        return queryRunner.query(sql,new BeanListHandler<>(Product.class),1,0,9);
    }
    @Override
    public List<Product> findByNew() throws SQLException {
        QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
        String sql = "select * from product where pflag=? order by pdate desc limit ?";
        return queryRunner.query(sql,new BeanListHandler<>(Product.class),0,9);
    }
    @Override
    public Product findById(String pid) throws SQLException {
        QueryRunner queryRunner = new
                QueryRunner(JDBCUtils.getDataSource());
        String sql = "select * from product where pid = ?";
        return queryRunner.query(sql,new BeanHandler<>(Product.class),pid);
    }
    @Override
    public int findTotalRecordByCid(String cid) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
        String sql = "select count(*) from product where cid = ? and pflag=?";
        Long count = (Long)queryRunner.query(sql,new ScalarHandler<>(),cid,0);
        return count.intValue();
    }
    @Override
    public List<Product> findAllByCid(String cid, int startIndex, int pageSize) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
        String sql = "select * from product where cid = ? and pflag = ? order by pdate desc limit ?,?";
        return queryRunner.query(sql,new BeanListHandler<>(Product.class),cid,0,startIndex,pageSize);
    }
}